﻿using ASPNetPatterns.Controllers;
using ASPNetPatterns.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ASPNetPatterns.Account
{
    public partial class LogIn : System.Web.UI.Page
    {
        IdentityAsp iasp;
        public IdentityAsp IdentityManager
        {
            get
            {
                if (iasp == null)
                    iasp = new IdentityAsp();
                return iasp;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Registro";
            HideErrorMessage();
        }

        private void HideErrorMessage()
        {
            ErrorMessage.Visible = false;
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (IdentityManager.AutenticarUsuario(Email.Text, Password.Text, RememberMe.Checked))
                    IdentityHelper.ReturnToDefaultLoginPage(Response);
            }
            catch (ASPNetPatterns.Models.IdentityAspException ex) 
            {
                SetErrorMessage(ex.Message);
            }
            catch (Exception)
            {
                SetErrorMessage("Error al autenticar el usuario. Verifica usuario y contraseña.");
            }
        }
        protected void SetErrorMessage(string text) 
        {
            ErrorMessage.Visible = true;
            FailureText.Text = text;
        }
    }
}